package addition.chat;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 聊天服务器。端口 9953
 */
public class ChatServer {

    /**
     * ObjectMapper
     */
    private final static ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 请求聊天机器人
     *
     * @param message 发送消息
     * @return 恢复消息
     */
    @SuppressWarnings("unchecked")
    public static String requestRobot(String message) throws IOException {
        String reqURL = String.format("https://api.ownthink.com/bot?appid=xiaosi&userid=user&spoken=%s",
                URLEncoder.encode(message, StandardCharsets.UTF_8));
        Map<String, Object> resp = MAPPER.readValue(new URL(reqURL), MAPPER.getTypeFactory()
                .constructMapType(Map.class, String.class, Object.class));

        String text = "(∪.∪ )...zzz";
        if ("success".equals(resp.get("message"))) {
            Map<String, Object> data = (Map<String, Object>) resp.get("data");
            Map<String, Object> info = (Map<String, Object>) data.get("info");
            text = (String) info.get("text");
        }

        return text;
    }

    /**
     * 从流中获取文本
     *
     * @param is InputStream
     * @return 文本
     * @throws IOException IOException
     */
    public static String getMessage(InputStream is, String charsetName) throws IOException {
        return new BufferedReader(new InputStreamReader(is, charsetName)).readLine();
    }

    public static void main(String[] args) throws IOException {
        try (ServerSocket server = new ServerSocket(8080)) {
            System.out.println("Server start.");
            while (true) {
                Socket client = server.accept();

                // Client request handle
                new Thread(() -> {
                    try {
                        SocketAddress address = client.getRemoteSocketAddress();
                        InputStream is = client.getInputStream();
                        OutputStream os = client.getOutputStream();

                        // Read message from client
                        String message = getMessage(is, "UTF-8");
                        System.out.printf("> %s: %s%n", address, message);

                        // Reply Message
                        String respMessage = requestRobot(message);
                        System.out.printf("> REPLY - [ %s ]: %s%n", address, respMessage);
                        os.write(respMessage.getBytes(StandardCharsets.UTF_8));
                        os.flush();
                        is.close();
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        }
    }

}
